package FileControl.Source;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import FileControl.FileControl;

public class MultiThread extends AbstractCopy {

	protected static ThreadPool pool;
	
	public static void threadedSync(File source, File dest) {
		pool = ThreadPool.getInstance();
		pool.start();
		sync(source,dest);
		pool.kill();
	}
	
	public static void copy(File source, File dest) {
		List<File> errors = new LinkedList<File>();
		if(!source.exists()) {
			println("Sync Error: source file-> " + source.getName() + " does NOT exist!");
		} else if(!source.isDirectory()) {
			//spawn copy thread
			pool.addTask(new CopyThread(source,dest));
		} else {
			if(!dest.exists()) {
				CopyDir.mkdir(dest);
			}
			for(File f : source.listFiles()) {
				if(f.isDirectory()) {
					copy(f,new File(dest.getPath() + "/" + f.getName()));
				}
				else {
					//spawn copy thread
					pool.addTask(new CopyThread(source,dest));
				}
			}
		}
	}
	
	public static void sync(File source, File dest) {
//		System.out.println(pool);
		if(!source.exists()) {
			println("Sync Error: source file-> " + source.getName() + " does NOT exist!");
		} else if(!source.isDirectory()) {
			syncFile(source,dest);
		} else {
			if(!dest.exists()) 
				CopyDir.mkdir(dest);
			
			for(File f : source.listFiles()) {
				if(f.isDirectory()) { 
					sync(f,new File(dest.getPath() + "/" +f.getName()));
				} else {
					syncFile(f,new File(dest.getPath() + "/" +f.getName()));
				}
			}
		} 
	}
	
	public static void syncFile(File source, File dest) {
//		println("Checking: " + source.getName() + " " + source.isDirectory());
		if(!source.exists()) {
			println("Sync Error: source file-> " + source.getName() + " does NOT exist!");
		} else if(!dest.exists()) {
			//spawn copy thread
			pool.addTask(new CopyThread(source,dest));
		} else {
			//check size
			if(source.length() > dest.length()) {
				dest.delete();
				pool.addTask(new CopyThread(source,dest));
			}
			//check date
			else if(source.lastModified() > dest.lastModified()) {
				dest.delete();
				//spawn copy thread
				pool.addTask(new CopyThread(source,dest));
			}
		}
	}
}
